// 请求拦截器
const baseURL = 'https://tea.qingnian8.com/api'  // 基础URL

export const request = (options = {}) => {
    return new Promise((resolve, reject) => {
        // 合并选项
        options.url = `${baseURL}${options.url}`
        options.method = options.method || 'GET'
        options.data = options.data || {}
        options.header = options.header || {}

        // 获取本地存储的token
        const token = uni.getStorageSync('token')
        if (token) {
            options.header.Authorization = `Bearer ${token}`
        }

        // 请求
        uni.request({
            ...options,
            success: (res) => {
                // 统一处理响应
                if (res.statusCode === 200) {
                    resolve(res.data)
                } else if (res.statusCode === 401) {
                    // token过期或未登录
                    uni.removeStorageSync('token')
                    uni.showToast({
                        title: '请先登录',
                        icon: 'none'
                    })
                    setTimeout(() => {
                        uni.redirectTo({
                            url: '/pages/login/login'
                        })
                    }, 1500)
                    reject(res)
                } else {
                    uni.showToast({
                        title: res.data.message || '请求失败',
                        icon: 'none'
                    })
                    reject(res)
                }
            },
            fail: (err) => {
                uni.showToast({
                    title: '网络错误',
                    icon: 'none'
                })
                reject(err)
            }
        })
    })
} 